package com.cn.wanxi.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(urlPatterns = {"*.html","/*"})
public class MyFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String path = req.getServletPath();//获取请求路径
        System.out.println(path);
        //如果不是访问的登录注册界面
        if (!(path.equals("/html/back/login.html")||path.equals("/back/login")) && !(path.equals("/html/back/register.html")||path.equals("/back/register"))&&path.startsWith("/back")){
            //session认证
            HttpSession session = req.getSession();
            Object username = session.getAttribute("username");
            if (username!=null){//不为空则放行
                filterChain.doFilter(req,resp);
            }else{//不存在则返回到登录界面
                resp.sendRedirect("/html/back/login.html");
            }
        }else{
            filterChain.doFilter(req,resp);
        }
    }
}
